//
//  OAuthViewController.swift
//  Weibo10
//
//  Created by zhangbaiqiang on 16/1/6.
//  Copyright © 2016年 itheima. All rights reserved.
//  2808002429
//  25947c517010a9bfeb00fb84e321ab4f

import UIKit
import SVProgressHUD

/// 授权控制器
class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    
    /**
     加载用户信息
     
     - parameter account: 账户
     */
    private func loadUserInfo(account: UserAccount) {
    
        NetworkTools.sharedTools.loadUserInfo(account.uid!, accessToken: account.access_token!) { (result, error) -> () in
            if error != nil {
                return
            }
            guard let dict = result as? [String: AnyObject] else {
                return
            }
            
            account.name = dict["name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
        }
    }
    // MARK: - 监听方法
    ///关闭
    @objc private func close() {
         dismissViewControllerAnimated(true, completion: nil)
    }
    
    ///自动填充 -- web 注入（以代码的方式向 web页面 添加内容)
    @objc private func autoLoagin() {
        let js = "document.getElementById('userId').value = '18120184391';" +
        "document.getElementById('passwd').value = 'haoren9051';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    // MARK: - 设置界面
    override func loadView() { //自定义view使用
        view = webView
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoLoagin")
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        //加载页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
        // Do any additional setup after loading the view.
    }
    
}



// MARK: - UIwebView 代理方法  跟踪重定向URL
extension OAuthViewController: UIWebViewDelegate {
    /**
     将要加载请求的代理方法
     
     - parameter webView:        webView
     - parameter request:        要加载的请求
     - parameter navigationType: 导航类型,页面跳转方式
     
     - returns: 是否加载当前请求
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request:NSURLRequest,  navigationType: UIWebViewNavigationType) -> Bool {
        // 目标: 授权回调地址如果是百度. 就不加载
        // 1 . 判断访问的1主机是否是www.baidu.com
        guard let url = request.URL where url.host == "www.baidu.com" else {
            return true
        }
        // 2. 从百度地址的url 中提取'code = '看是否存在,如果没有授权码,说明授权取消
        guard let query = url.query where query.hasPrefix("code=") else {
            print("取消授权")
            return false
        }
        // 3. 从query字符串中提取"code="后面的授权码
        let code = query.substringFromIndex("code=".endIndex)
        print(query)
        print("授权码是" + code)
        
        
        //4. 加载accessToken
        NetworkTools.sharedTools.loadAccessToken(code, finished: { (result, error) -> () in
            
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            let account = UserAccount(dict: result as! [String: AnyObject])
            self.loadUserInfo(account)
        })
        
        return false
    }
    //如果url以会提哦啊地址开始,需要检查查询参数
    //其他URl均加载

    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        //判断是否应为用户中断
        if error?.code == 102 {
            SVProgressHUD.dismiss()
        } else {
            SVProgressHUD.showInfoWithStatus("网络不行")
        }
    }
    
    
}

